//
//  BTimer.swift
//  AnniekidsiPad
//
//  Created by 魏滨 on 2020/3/10.
//  Copyright © 2020 Anniekids. All rights reserved.
//

import UIKit

enum BTimerState {
    case start
    case stop
    case resume
    case suspend
}

class BTimer {
    ///  定时器状态
   private static var state: BTimerState = .stop
    
    /// 开启定时器 （总时长=timeInterval*totalTrigger）
    /// - Parameters:
    ///   - timerName: 定时器名字
    ///   - timeInterval: 时间间隔
    ///   - totalTrigger: 总触发次数
    ///   - queue: 队列
    ///   - block: 执行任务的闭包
    ///   - complete: 定时器结束任务闭包
    class func start(timerName: String?, timeInterval: TimeInterval, totalTrigger: TimeInterval, queue: DispatchQueue, block: ((_ info: BTimerModel)->Void)? = nil, complete: (()->Void)? =  nil) {
        let name = timerName ?? "nil"
        var timer = shared.timerContainer[name]
        if timer == nil {
            state = .start
            timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
            timer?.resume()
            shared.timerContainer[name] = timer
        }
        var rate: TimeInterval = 0
        //精度0.1秒
        timer?.schedule(deadline: .now(), repeating: timeInterval, leeway: DispatchTimeInterval.milliseconds(100))
        timer?.setEventHandler(handler: {
            rate += 1
            let model = BTimerModel.init(timerName: name, timeInterval: timeInterval, queue: queue, trigger: rate, totalDuration: totalTrigger * timeInterval, remainingDuration: (totalTrigger * timeInterval) - (rate * timeInterval))
            block?(model)
            if rate >= totalTrigger {
                self.cancel(timerName: name)
                complete?()
            }
        })
    }
    
    /// 取消定时器
    /// - Parameter timerName: 定时器名字
    class func cancel(timerName: String?) {
        let name = timerName ?? "nil"
        let timer = shared.timerContainer[name]
        shared.timerContainer.removeValue(forKey: name)
        if state == .suspend {
            timer?.resume()
            state = .resume
        }
        timer?.cancel()
        print("定时器\(name)挂了")
        state = .stop
    }
    
    /// 恢复定时器
    /// - Parameter timerName: 定时器名字
    class func resume(timerName: String?) {
        guard state != .resume else {
            return
        }
        let name = timerName ?? "nil"
        let timer = shared.timerContainer[name]
        timer?.resume()
        print("定时器\(name)恢复")
        state = .resume
    }
    
    /// 暂停定时器
    /// - Parameter timerName: 定时器名字
    class func suspend(timerName: String?) {
        guard state != .suspend else {
            return
        }
        let name = timerName ?? "nil"
        let timer = shared.timerContainer[name]
        timer?.suspend()
        print("定时器\(name)暂停")
        state = .suspend
    }
    
    /// 检查定时器是否已存在
    ///
    /// - Parameter name: 定时器名字
    /// - Returns: 是否已经存在定时器
    class func isExistTimer(timerName: String?) -> Bool {
        guard let name = timerName else { return false }
        if shared.timerContainer[name] != nil {
            return true
        }
        return false
    }
    
    private static let shared = BTimer()
    private lazy var timerContainer = [String: DispatchSourceTimer]()

}


struct BTimerModel {
    /// 定时器名称
    var timerName: String = ""
    /// 时间间隔
    var timeInterval: TimeInterval = 0
    /// 队列
    var queue: DispatchQueue = .main
    /// 触发次数
    var trigger: TimeInterval = 0
    /// 总时长
    var totalDuration: TimeInterval = 0
    /// 剩余时间
    var remainingDuration: TimeInterval = 0
    /// 已用时长
    var elapsedDuration: TimeInterval {
       return totalDuration - remainingDuration
    }
    
}
